import pdb
import os, sys
import MySQLdb

class MyConn:

    def __init__(self, param, table_name):
        self.param      = param
        self.table_name = table_name

        # TODO
        # - place DB passwords somewhere
        # - parent class??
        try:
            self._conn = MySQLdb.connect(host="localhost", user="healthopia", passwd="h3althopiA", db="healthopia")

        except MySQLdb.OperationalError, err:
            print 'Error - ' + str(err)
            sys.exit(2) 


class Keywords(MyConn):

    def search_keyword(self, alias):
        _cursor = self._conn.cursor()
        sql     = 'SELECT keyword FROM ' + self.table_name + ' WHERE alias LIKE %s' 
        _cursor.execute(sql, ((alias,)))
        row = _cursor.fetchone()

        if row is not None:
            # value               = {}
            # value['keyword']    = row[0]
            value   = row[0]

            return value

        else:
            return None

class MappedTags(MyConn):

    def search(self, tag):
        _cursor = self._conn.cursor()
        sql     = 'SELECT tag, symptom_name FROM ' + self.table_name + ' WHERE tag = %s' 
        _cursor.execute(sql, ((tag,)))
        row = _cursor.fetchone()

        if row is not None:
            value                   = {}
            value['tag']            = row[0]
            value['symptom_name']   = row[1]

            return value

        else:
            return None

    def insert(self, tag, symptom_name):
        _cursor = self._conn.cursor()
        sql     = 'INSERT INTO ' + self.table_name + ' (tag, symptom_name) values (%s, %s)' 
        _cursor.execute(sql, ((tag, symptom_name)))
        self._conn.commit()

class MsgContent(MyConn):

    def search_by_name(self, content_name):
        _cursor = self._conn.cursor()
        sql     = 'SELECT name, message, tcsd FROM ' + self.table_name + ' WHERE name LIKE %s' 
        _cursor.execute(sql, ((content_name,)))
        row = _cursor.fetchone()

        if row is not None:
            value               = {}
            value['name']       = row[0]
            value['message']    = row[1]
            value['tcsd']       = row[2]

            return value

        else:
            # TODO
            # - execute a search via tags???

            return None

    def insert_content(self, name, message, tags, tcsd):
        _cursor = self._conn.cursor()
        sql     = 'INSERT INTO ' + self.table_name + ' (name, message, tags, tcsd) values (%s, %s, %s, %s)' 
        _cursor.execute(sql, ((name, message, tags, tcsd)))
        self._conn.commit()
